﻿namespace WebSilverlight.Controls
{    
    using System.Collections.ObjectModel;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using WebSilverlight.Helpers;
    using System.IO;    

    public partial class PictureControl : ChildWindow
    {
        #region Properties
            CaptureSource _captureSource;
            ObservableCollection<WriteableBitmap> _images = new ObservableCollection<WriteableBitmap>();
            public WriteableBitmap Current { get; set; }
            public bool SelectionChanged { get; set; }
            public bool SavePicture { get; set; }
        #endregion

        public PictureControl()
        {
            InitializeComponent();
            SelectionChanged = false;
            SavePicture = false;
            Loaded += new RoutedEventHandler(Page_Loaded);
        }

        void Page_Loaded(object sender, RoutedEventArgs e)
        {            
            // Get the list of video sources            
            this.VideoSources.ItemsSource = CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices();
            if (this.VideoSources.Items.Count == 0)
            {                
                this.btn_StartCapture.IsEnabled = false;
                this.ControlError.Visibility = System.Windows.Visibility.Visible;
                this.CameraActions.Visibility = System.Windows.Visibility.Collapsed;
                this.ErrorText.Text = "No available Video Source";
            }            

            // 
            this._captureSource = new CaptureSource();
            this._captureSource.CaptureImageCompleted += ((s, args) =>
            {
                // Add the picture to the collection, and mark it as selected
                this._images.Add(args.Result);
                this.Snapshots.SelectedIndex = _images.Count - 1;
            });

            // bind snapshots list box with images collection
            this.Snapshots.ItemsSource = _images;

            // Loads the Current Image
            if (this.Current != null)
            {
                ImageBrush imgBrush = new ImageBrush();
                imgBrush.ImageSource = Current;
                // paint the Image brush on the rectangle
                this.WebcamCapture.Fill = imgBrush;
                this._images.Add(Current);
                this.Snapshots.SelectedIndex = 0;
            }
        }

        private void CaptureButton_Click(object sender, RoutedEventArgs e)
        {
            StartCapture();
        }
        private void VideoSource_Selected(object sender, SelectionChangedEventArgs e)
        {
            StartCapture();
        }

        private void StopCapture_Click(object sender, RoutedEventArgs e)
        {
            StopCapture();
        }

        private void TakeSnapshot_Click(object sender, RoutedEventArgs e)
        {
            if (this._captureSource != null)
            {
                // capture the current frame and add it to our observable collection                
                this._captureSource.CaptureImageAsync();
            }
        }
        
        private void StopCapture()
        {
            if (this._captureSource != null && this.VideoSources.Items.Count > 0)
            {
                this._captureSource.Stop();
                this.btn_StartCapture.IsEnabled = true;
                this.btn_StopCapture.IsEnabled = false;
                this.btn_TakeSnapshot.IsEnabled = false;
            }
        }

        private void StartCapture()
        {
            if (this._captureSource != null)
            {
                if (this.VideoSources.SelectedItems.Count != 1)
                {
                    System.Windows.MessageBox.Show("Select a Video Source");
                }
                else
                {
                    this.btn_StartCapture.IsEnabled = false;
                    this.btn_StopCapture.IsEnabled = true;
                    this.btn_TakeSnapshot.IsEnabled = true;

                    // stop whatever device may be capturing
                    this._captureSource.Stop(); 
                    // set the devices for the selected capture source
                    this._captureSource.VideoCaptureDevice = (VideoCaptureDevice)VideoSources.SelectedItem;
                    // create the brush
                    VideoBrush vidBrush = new VideoBrush();
                    vidBrush.SetSource(_captureSource);
                    // paint the video brush on the rectangle
                    this.WebcamCapture.Fill = vidBrush;
                    // request user permission and display the capture
                    if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess())
                    {
                        this._captureSource.Start();
                    }
                }
            }
        }

        private void SaveSnapshot_Click(object sender, RoutedEventArgs e)
        {
            StopCapture();            
            this.SavePicture = true;
            Close();            
        }

        private void Snapshot_Selected(object sender, SelectionChangedEventArgs e)
        {
            if (this.Snapshots.SelectedItems.Count == 1)
            {
                this.Current = (WriteableBitmap)this.Snapshots.SelectedItem;
                this.SelectionChanged = true;
                this.btn_SaveSnapshot.IsEnabled = true;

                // Stop the capture and display selected picture
                StopCapture();
                ImageBrush imgBrush = new ImageBrush();
                imgBrush.ImageSource = Current;
                this.WebcamCapture.Fill = imgBrush;
            }
        }

        private void UpLoad_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Jpeg Files (.jpg)|*.jpg|Bmp Files (.bmp)|*.bmp|Png Files (.png)|*.png|All Files (.*)|*.*";
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog().Value)
            {
                using (Stream srcStream = openFileDialog.File.OpenRead())
                {
                    // Load Selected File
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(srcStream);                                        
                    WriteableBitmap bmp = new WriteableBitmap(bitmapImage);
                    // Add image to the Collection, and mark it as selected.
                    _images.Add(bmp);
                    this.Snapshots.SelectedIndex = _images.Count - 1;
                }
            }            
        }        
    }
}